<template>
	<view class="bigBox">
		<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper"
			@scrolltolower="lower" @scroll="scroll">
			<view class="box">
				<view class="bookBox" v-for="(item,index) in novelList" :key="index">
					<view class="leftImage">
						<image :src="item.pictureBase64" mode="" @click="handleNovel(item,index)"></image>
						<image v-show="isPut" class="rightSign"
							:src="item.flag?'/static/image/checked.png':'/static/image/uncheck.png'"
							mode=""></image>
					</view>
					<view class="rightTitle">
						{{item.bookName}}
					</view>
				</view>
				<view :class="flag?'active':'meun'" @click="handleOpen">
					<template v-if="flag">
						<view class="child" v-for="(item,index) in meunList" :key="index"
							@click.stop="handleMeun(item,index)">
							<text :style="{color:item.able?item.color:'#ccc'}">{{item.meunTitle}}</text>
							<image v-show="!item.able" src="/static/image/disableuse.png" mode=""></image>
						</view>
					</template>
					<template v-else>
						<view class="child">
							菜单
						</view>
					</template>

				</view>
				<view class="tipBox" v-if="novelList.length==0">
					杜绝书荒，由你引领，赶快去专区下载吧！
				</view>
			</view>
		</scroll-view>

	</view>

</template>

<script>
	import {
		mapState,
		mapGetters,
		mapMutations,
		mapActions
	} from 'vuex';
	import fileApi from "@/uni_modules/hbh-fileIo/js_sdk/index.js"
	export default {
		data() {
			return {
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				flag: false,
				meunList: [],
				novelList: [],
				isPut: false,
				scrollTop: 0,
				old: {
					scrollTop: 0
				}
			};
		},
		onBackPress(options) {
			if (options.from === 'navigateBack') {
				return false
			}
			this.back();
			return true
		},
		onLoad() {
			this.getTxtNovel()
		},
		methods: {
			...mapMutations(["home/deleteDownList","home/rushHomeTxtBox"]),
			back() {
				this["home/rushHomeTxtBox"]() //返回通知刷新
				uni.navigateBack()
			},
			upper: function(e) {
				// console.log(e)
			},
			lower: function(e) {
				console.log(e)
			},
			scroll: function(e) {
				// console.log(e)
				this.old.scrollTop = e.detail.scrollTop
			},
			goTop: function(e) {
				// 解决view层不同步的问题
				this.scrollTop = this.old.scrollTop
				this.$nextTick(function() {
					this.scrollTop = 0
				});
				uni.showToast({
					icon: "none",
					title: "纵向滚动 scrollTop 值已被修改为 0"
				})
			},
			handleNovel(item, index) {
				if (this.isPut) { //编辑状态就切换选中状态
					item.flag = !item.flag
				} else { //正常就进入阅读页
					uni.navigateTo({
						url: `/pages/txtNovelContent/txtNovelContent?bookName=${item.bookName}&fileNameId=${item.fileNameId}&authorName=${item.authorName}&totalNumber=${item.totalNumber}`
					})
				}
			},
			//获取本地小说
			getTxtNovel() {
				plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, (fs) => {
					// fs.root是根目录操作对象DirectoryEntry
					// 创建读取目录信息对象 
					var directoryReader = fs.root.createReader();
					directoryReader.readEntries((entries) => {
						if (entries.length == 0) {
							return
						}
						let index = entries.findIndex(item => item.name == 'downloadTxt')
						if (index != -1) {
							this.downTxtFileName()
						} else {
							console.log("本地小说目录未创建！")
						}
					}, function(e) {
						alert("Read entries failed: " + e.message);
					});
				});


			},
			//调用获取downTxt目录文件名
			async downTxtFileName() {
				const res = await fileApi.getFileList('documents/downloadTxt')
				if (res.code !== 200) {
					return
				}
				res.data.forEach((item, index) => {
					fileApi.getFileList('documents/downloadTxt/' + item.name).then(async(out) => {
						let isSuccess=out.data.find(item=>item.name=='success')
							if (out.code == 200 && isSuccess) {
								const pic=await fileApi.getFileList('documents/downloadTxt/' + item.name+"/base64")
								let index1 = out.data.findIndex(item => item.name.indexOf(".txt")!=-1)
								fileApi.getFileData(pic.data[0].fullPath).then((result) => {
									this.novelList.push({
										bookName:out.data[index1].name.slice(0,-4),
										authorName:pic.data[0].name.split("@@")[0],
										totalNumber:pic.data[0].name.split("@@")[1].slice(0,-4),
										flag: false,
										fileNameId: item.name,
										pictureBase64: result.result
									})
								}).catch((err)=>{
									console.log(err)
								})
							}
						})
						.catch((err) => {
							console.log(err)
						})
				})

			},
			handleOpen(event) {
				if (this.novelList.length > 0) {
					if (!this.flag) {
						this.flag = true
						setTimeout(() => {
							this.meunList = [{
								meunTitle: '全选',
								color: '#00aa00',
								able: false
							}, {
								meunTitle: '编辑',
								color: '#00aaff',
								able: true
							}, {
								meunTitle: '删除',
								color: '#ff0000',
								able: false
							}, {
								meunTitle: '关闭',
								color: '#000000',
								able: true
							}]
						}, 500)
					}
				} else {
					uni.showToast({
						icon: "none",
						title: "当前没有下载小说，无法使用！"
					})
				}

			},
			async deleteArr(arr) {
				uni.showLoading({
					mask: true,
					title: "正在清理",
					icon: "none"
				})
				let i = 0
				while (i < arr.length) {
					const hres = await fileApi.delDirectory('documents/downloadTxt/' + arr[i].fileNameId)
					if (hres.code == 200) {
						//删除storage记录
						if (uni.getStorageSync("txtLocalHistoryList")) {
							let arr2 = JSON.parse(uni.getStorageSync("txtLocalHistoryList"))

							let b = arr2.findIndex(item => item.fileNameId == arr[i].fileNameId)
							console.log(b, arr[i].fileNameId, arr2)
							if (b != -1) {
								arr2.splice(b, 1)
								uni.setStorageSync("txtLocalHistoryList", JSON.stringify(arr2))
							}
						}
						//删除vuex记录
						let hIndex = this.novelList.findIndex(item => item.fileNameId == arr[i].fileNameId)
						if (hIndex != -1) {
							this["home/deleteDownList"]({
								fileNameId: arr[i].fileNameId
							})
							this.novelList.splice(hIndex, 1)
						}
					}
					i++
				}
				uni.hideLoading()
			},
			//删除下章
			downDelete(arr) {
				uni.showModal({
					title: '提示',
					content: '您确定删除本地选中小说吗？',
					success: async (res) => {
						if (res.cancel) {
							// console.log('用户点击取消');
							return
						}
						this.deleteArr(arr)
					}
				});
			},
			handleMeun(item, index) {
				if (!item.able) {
					uni.showToast({
						icon: "none",
						title: "请先点击编辑使用！"
					})
					return
				}
				switch (index) {
					case 0: //全选
						if (item.meunTitle == '全选') {
							this.novelList.map(item => item.flag = true)
							item.meunTitle = '反选'
							break;
						}
						this.novelList.map(item => item.flag = false)
						item.meunTitle = '全选'
						break;
					case 1:
						if (item.meunTitle == '编辑') {
							this.isPut = true
							item.meunTitle = '取消'
							this.novelList.map(item => item.flag = false)
							this.meunList[0].meunTitle = '全选'
							this.meunList[0].able = true
							this.meunList[2].able = true
							break;
						}
						this.isPut = false
						item.meunTitle = '编辑'
						this.meunList[0].able = false
						this.meunList[2].able = false
						break;
					case 2: //删除
						let arr = this.novelList.filter(item => item.flag)
						if (arr.length == 0) {
							uni.showToast({
								icon: "none",
								title: "请选中要删除的小说！"
							})
							break;
						}
						this.downDelete(arr)
						break;
					case 3:
						this.meunList = []
						this.flag = false
						this.isPut = false
						break;
					default:
						break;
				}
			}
		}
	}
</script>

<style lang="scss">
	// page {
	// 	background-image: linear-gradient(0deg, #ccc, #aaaa00 40%, #55aa7f);
	// 	background-repeat: no-repeat;
	// 	background-size: 100% 100%;
	// }
	.bigBox {
		height: 100vh;
	}

	.scroll-Y {
		height: 100%;
		background-image: linear-gradient(0deg, #ccc, #aaaa00 40%, #55aa7f);
		background-repeat: no-repeat;
		background-size: 100% 100%;
	}

	.tipBox {
		position: fixed;
		top: calc(100vh / 2 - 100rpx);
		width: 100vw;
		height: 200rpx;
		left: 0rpx;
		color: #ccc;
		font-size: 30rpx;
		font-weight: bolder;
		line-height: 200rpx;
		text-align: center;
	}

	.box {
		display: flex;
		flex-wrap: wrap;
		padding: 30rpx;
		box-sizing: border-box;

		.active {
			position: fixed;
			bottom: 30rpx;
			border-radius: 50rpx;
			right: 30rpx;
			width: calc(100vw - 60rpx);
			height: 100rpx;
			background-color: #dcdcdc;
			line-height: 100rpx;
			text-align: center;
			transition: all .5s linear 0s;
			display: flex;
			justify-content: space-between;
			overflow: hidden;

			.child {
				width: 25%;
				height: 100%;
				position: relative;
				display: flex;
				justify-content: center;
				align-items: center;

				image {
					width: 36rpx;
					height: 36rpx;
					position: absolute;
					top: calc(50% - 18rpx);
					left: calc(50% - 18rpx);
				}
			}
		}

		.meun {
			position: fixed;
			bottom: 30rpx;
			border-radius: 50%;
			right: 30rpx;
			width: 100rpx;
			height: 100rpx;
			background-color: #dcdcdc;
			line-height: 100rpx;
			text-align: center;
			transition: all .5s linear 0s;
			display: flex;
			overflow: hidden;

			.child {
				width: 100%;
				height: 100%;
			}
		}

		.bookBox {
			width: 25%;
			height: 300rpx;
			margin-bottom: 20rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.leftImage {
				width: 150rpx;
				height: 200rpx;
				border-radius: 10rpx;
				overflow: hidden;
				box-shadow: 5rpx 5rpx 10rpx #ccc;
				position: relative;

				image {
					width: 100%;
					height: 100%;
				}

				.rightSign {
					position: absolute;
					top: 0rpx;
					right: 0rpx;
					width: 36rpx;
					height: 36rpx;
				}
			}

			.rightTitle {
				margin-top: 20rpx;
				height: 80rpx;
				color: #efefef;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				/* 显示行数 */
				overflow: hidden;
				font-size: 30rpx;
				text-overflow: ellipsis;
			}
		}
	}
</style>